package com.demo.result;

import java.util.Objects;

/**
 * @author wangfengchen
 */
public class CommonResult<T> {

  private Integer code;
  private String msg;
  private T data;

  /**
   * 返回错误，可以传code和msg
   *
   * @param code
   * @param msg
   * @return
   */
  public static <T> CommonResult<T> error(Integer code, String msg) {
    return setResult(code, msg, null);
  }

  /**
   * 返回错误，可以传msg
   *
   * @param msg
   * @return
   */
  public static <T> CommonResult<T> error(String msg) {
    return setResult(ResultCode.ERROR.getCode(), msg, null);
  }

  /**
   * 返回错误，默认值
   *
   * @return
   */
  public static <T> CommonResult<T> error() {
    return setResult(ResultCode.ERROR.getCode(), ResultCode.ERROR.getMessage(),
        null);
  }

  /**
   * 返回成功，可以传data
   *
   * @param data
   * @return
   */
  public static <T> CommonResult<T> success(T data) {
    return setResult(ResultCode.SUCCESS.getCode(),
        ResultCode.SUCCESS.getMessage(), data);
  }

  /**
   * 返回成功，不传data
   *
   * @return
   */
  public static <T> CommonResult<T> success() {
    return setResult(ResultCode.SUCCESS.getCode(),
        ResultCode.SUCCESS.getMessage(), null);
  }

  /**
   * 返回成功，可以传msg和data
   *
   * @param msg
   * @return
   */
  public static <T> CommonResult<T> success(String msg, T data) {
    return setResult(ResultCode.SUCCESS.getCode(), msg, data);
  }

  /**
   * 返回成功，可以传msg
   *
   * @param msg
   * @return
   */
  public static <T> CommonResult<T> success(String msg) {
    return setResult(ResultCode.SUCCESS.getCode(), msg, null);
  }

  /**
   * 通用封装
   *
   * @param code
   * @param msg
   * @param data
   * @return
   */
  private static <T> CommonResult<T> setResult(Integer code, String msg,
      T data) {
    return new CommonResult<>(code, msg, data);
  }

  /**
   * 判断数据库操作的返回结果
   *
   * @param result
   * @return
   */
  public static boolean isSuccess(int result) {
    return result > 0;
  }

  /**
   * 判断调用接口返回状态码
   *
   * @param baseResult
   * @return
   */
  public static boolean isSuccess(CommonResult<?> baseResult) {
    return baseResult != null && Objects.equals(baseResult.getCode(),
        ResultCode.SUCCESS.getCode());
  }

  public CommonResult() {
  }

  public CommonResult(Integer code, String msg, T data) {
    this.code = code;
    this.msg = msg;
    this.data = data;
  }

  public Integer getCode() {
    return code;
  }

  public void setCode(Integer code) {
    this.code = code;
  }

  public String getMsg() {
    return msg;
  }

  public void setMsg(String msg) {
    this.msg = msg;
  }

  public T getData() {
    return data;
  }

  public void setData(T data) {
    this.data = data;
  }
}
